package com.dhcc.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Message.RecipientType;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.dhcc.utils.mail.MailSetting;

/**
 * 邮件处理
 * 
 * @author hibean
 *
 */
public class __Mail {

	/**
	 * 发送邮件
	 */
	public static void sendSimpleMail(String receiver, String title, String content) {
		try {
			MailSetting setting = MailSetting.INSTANCE;
			Authenticator authenticator = new MyAuthenticator(setting);
			Session session = Session.getDefaultInstance(setting, authenticator);
			Message mailMessage = new MimeMessage(session);
			Address from = new InternetAddress(setting.getFrom(), setting.getFromName());
			mailMessage.setFrom(from);
			if(receiver.contains(";")) {
				String[] strs = receiver.split(";");
				Address[] to = new Address[strs.length];
				for (int i = 0; i < strs.length; i++) {
					to[i] = new InternetAddress(strs[i]);
				}
				mailMessage.setRecipients(RecipientType.TO, to);
			}else {
				Address to = new InternetAddress(receiver);
				mailMessage.setRecipient(RecipientType.TO, to);
			}
			mailMessage.setSubject(title);
			mailMessage.setText(content);
			Transport.send(mailMessage);
		} catch (Exception ex) {
			throw new RuntimeException("发送邮件失败", ex);
		}
	}

	private static class MyAuthenticator extends Authenticator {

		private MailSetting setting;

		public MyAuthenticator(MailSetting setting) {
			this.setting = setting;
		}

		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(setting.getUser(), setting.getPwd());
		}
	}
}
